package fr.sedoo.commons.client.widget.table.multiline;

import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.SafeHtmlRenderer;

import fr.sedoo.commons.client.util.SeparatorUtil;

/**
 * A renderer that display a single line input on several lines. Token are split
 * according to a token Default separator is
 * {@link SeparatorUtil.PIPE_SEPARATOR}
 */
public class MultilineRenderer implements SafeHtmlRenderer<String> {

	private static MultilineRenderer instance;
	private String separator = SeparatorUtil.PIPE_SEPARATOR;

	/**
	 * Singleton-mode access to the default separator renderer
	 */
	public static MultilineRenderer getInstance() {
		if (instance == null) {
			instance = new MultilineRenderer();
		}
		return instance;
	}

	/**
	 * This constructor is private to force the use of the singleton
	 */
	private MultilineRenderer() {
	}

	/**
	 * Constructor with a custom separator
	 */
	public MultilineRenderer(String separator) {
		this.separator = separator;
	}

	public SafeHtml render(String object) {
		if (object == null) {
			return SafeHtmlUtils.EMPTY_SAFE_HTML;
		} else {
			String asString = SafeHtmlUtils.fromString(object).asString();
			return SafeHtmlUtils.fromTrustedString(asString.replace(separator, "<br/>"));
		}
	}

	public void render(String object, SafeHtmlBuilder appendable) {

		if (object == null) {
			appendable.append(SafeHtmlUtils.fromString(object));
		} else {
			String asString = SafeHtmlUtils.fromString(object).asString();
			appendable.append(SafeHtmlUtils.fromTrustedString(asString.replace(separator, "<br/>")));
		}
	}

}
